package com.holyn.guofang.presenter;

import com.apkfuns.logutils.LogUtils;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Holyn on 2017/6/12.
 */

public abstract class AbstractBasePresenterImp implements BasePresenter {

    private Map<Integer, Disposable> disposableMap;

    private BaseView baseView;

    public AbstractBasePresenterImp(BaseView baseView) {
        this.baseView = baseView;
        disposableMap = new HashMap<>();
    }

    @Override
    public void resume() {

    }

    @Override
    public void dispose(Integer requestAction) {
        Disposable disposable = disposableMap.get(requestAction);
        if (disposable != null) {
            if (!disposable.isDisposed()) {
                disposable.dispose();
            }
        }
    }

    protected void addDisposable(Integer requestAction, Disposable disposable) {
        disposableMap.put(requestAction, disposable);
    }

    protected void requestStart(Integer requestAction) {
        baseView.requestStart(requestAction);
    }

    protected void requestError(Integer requestAction, Throwable e) {
        baseView.requestError(requestAction, e);
    }

    protected void requestComplete(Integer requestAction) {
        baseView.requestComplete(requestAction);
    }

    protected <T> Observable<T> getCommonObservable(final Integer requestAction, Observable<T> observable) {
        requestStart(requestAction);
        return observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Disposable disposable) throws Exception {
                        addDisposable(requestAction,disposable);
                    }
                })
                .doOnError(new Consumer<Throwable>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Throwable throwable) throws Exception {
                        requestError(requestAction, throwable);
                    }
                })
                .doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                        requestComplete(requestAction);
                    }
                });
    }

}
